import { nextTick, App } from 'vue'

export default function useDragWindowDirective(app: App): void {
  app.directive('drag-window', async (el) => {
    await nextTick()

    const modal = el
    const header = el.getElementsByClassName('drag-title')[0]
    let left = 0
    let top = 0
    header.style.cursor = 'move'
    top = top || modal.offsetTop
    header.onpointerdown = (e: { clientX: number; clientY: number; pointerId: number }) => {
      const startX = e.clientX
      const startY = e.clientY
      header.left = header.offsetLeft
      header.top = header.offsetTop
      header.setPointerCapture(e.pointerId)
      el.onpointermove = (event: { clientX: number; clientY: number }) => {
        console.log(event.clientX, event.clientY, '====================')
        const endX = event.clientX
        const endY = event.clientY
        modal.left = header.left + (endX - startX) + left
        modal.top = header.top + (endY - startY) + top
        modal.style.left = modal.left + 'px'
        modal.style.top = modal.top + 'px'
        console.log(modal, 'modal')
      }
      el.onpointerup = () => {
        left = modal.left || 0
        top = modal.top || 0
        el.onpointermove = null
        el.onpointerup = null
        header.releasePointerCapture(e.pointerId)
      }
    }
  })
}
// import { nextTick, App } from 'vue'

// export default function useDragWindowDirective(app: App): void {
//   app.directive('drag-window', async (el) => {
//     await nextTick()

//     const modal = el
//     const header = el.getElementsByClassName('drag-title')[0]
//     let isDragging = false // 新增拖动状态标识
//     let left = 0
//     let top = 0
//     header.style.cursor = 'move'
//     top = top || modal.offsetTop

//     header.onpointerdown = (e: PointerEvent) => {
//       // 排除关闭按钮的点击
//       const closeBtn = (e.target as HTMLElement).closest('.close-btn')
//       if (closeBtn) return

//       isDragging = true // 标记开始拖动
//       const startX = e.clientX
//       const startY = e.clientY
//       header.left = header.offsetLeft
//       header.top = header.offsetTop
//       header.setPointerCapture(e.pointerId)

//       el.onpointermove = (event: PointerEvent) => {
//         if (!isDragging) return
//         const endX = event.clientX
//         const endY = event.clientY
//         modal.left = header.left + (endX - startX) + left
//         modal.top = header.top + (endY - startY) + top
//         modal.style.left = modal.left + 'px'
//         modal.style.top = modal.top + 'px'
//       }

//       el.onpointerup = () => {
//         isDragging = false // 清除拖动状态
//         left = modal.left || 0
//         top = modal.top || 0
//         el.onpointermove = null
//         el.onpointerup = null
//         header.releasePointerCapture(e.pointerId)
//       }
//     }
//   })
// }
